class Snake {
  constructor(body, direction, mapWidth, mapHeight) {
    Object.assign(this, { body, direction, mapWidth, mapHeight });
  }

  step() {
    for (let i = this.body.length - 1; i > 0; i--) {
      this.body[i] = this.body[i - 1];
    }
    const head = Object.assign({}, this.body[0]);
    switch (this.direction) {
      case "left":
        head.x--;
        break;
      case  "right":
        head.x++;
        break;
      case  "top":
        head.y--;
        break;
      case  "down":
        head.y++;
        break;
    }
    this.body[0] = head;

    // 撞墙
    if (head.x < 0 || head.x >= this.mapWidth - 1 || head.y < 0 || head.y >= this.mapHeight - 1) {
      throw new Error("游戏失败！");
    }

    console.log(this.body.slice(1), head);
    // 蛇头撞到蛇身
    if (this.body.slice(1).some(p => p.x === head.x && p.y === head.y)) {
      throw new Error("游戏失败！");
    }
  }
}
